package cn.pugle.base.uri_encode;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;

import java.io.UnsupportedEncodingException;
import java.util.List;

import static cn.pugle.base.uri_encode.UriEncodeTest.encodeURIComponent;

public class FormURIEncodeEntity extends StringEntity {

	public FormURIEncodeEntity(final List<? extends NameValuePair> parameters,
                               final String encoding) throws UnsupportedEncodingException {
		super(converToString(parameters));
		setContentType(URLEncodedUtils.CONTENT_TYPE + HTTP.CHARSET_PARAM + (encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET));
	}

	private static String converToString(
			List<? extends NameValuePair> params) {
		StringBuilder queryParam = new StringBuilder("");
		for (NameValuePair param : params) {
//                queryParam.append(param.toString() + "&");
			queryParam.append(encodeURIComponent(param.getName())).append("=").append(encodeURIComponent(param.getValue())).append("&");
		}
		queryParam.deleteCharAt(queryParam.length() - 1);
		return queryParam.toString();
	}

	public FormURIEncodeEntity(final List<? extends NameValuePair> parameters)
			throws UnsupportedEncodingException {
		this(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
	}
}
